package com.tencent.dao;


import com.tencent.util.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.util.List;

/**
 * @author: Fame
 * @date: 2022-05-25 10:16
 * @description:
 */
public abstract class BaseDAO {

    private QueryRunner runner = new QueryRunner();



    /**
     * 增删改
     * @param sql
     * @param args
     * @return
     */
    public int update(String sql,Object...args){
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            return   runner.update(conn, sql, args);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(conn,null,null);
        }
        return -1;
    }

    /**
     * 查单个数据
     * @param T
     * @param sql
     * @param args
     * @param <T>
     * @return
     */
    public <T> T queryForBean(Class<T> T,String sql,Object...args){
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            return runner.query(conn,sql,new BeanHandler<T>(T),args);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(conn,null,null);
        }
        return null;
    }


    /**
     * 查询多条数据
     * @param T
     * @param sql
     * @param args
     * @param <T>
     * @return
     */
    public <T>List<T> queryForList(Class<T> T,String sql,Object...args){
        Connection conn = null;

        try {
            conn = JDBCUtils.getConnection();
            return runner.query(conn,sql,new BeanListHandler<T>(T),args);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(conn,null,null);
        }
        return null;
    }

    /**
     * 查询特数据
     * @param sql
     * @param args
     * @return
     */
    public Object queryForSingeValue(String sql,Object...args){
        try {
            Connection conn = JDBCUtils.getConnection();
            return runner.query(conn,sql,new ScalarHandler(),args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
